package api

import (
	"context"
	_const "longmen/server/pkg/common/helper/const"
	"longmen/server/pkg/common/helper/util"
	"longmen/server/pkg/common/services"
	"strings"
	"time"

	"github.com/labstack/echo/v4"
	"github.com/spf13/cast"
)

type Controller struct {
	*services.Service
}

func (base Controller) BindAndValid(ctx echo.Context, req interface{}) error {
	if err := util.Json2Struct(ctx.Get(_const.HTTP_KEY_BODY).(string), &req); err != nil {
		return err
	}

	if err := _const.Validate.Struct(req); err != nil {
		return err
	}
	return nil
}

func (base Controller) GetAuthUserId(c echo.Context) int {
	var uid int
	uid = cast.ToInt(util.GetCookie(c, "uid"))
	authorization := strings.Split(c.Request().Header.Get("authorization"), ";")
	if len(authorization) >= 2 { //截取请求头中 token 和 uid
		tokenSlice := strings.Split(authorization[0], "=")
		uidSlice := strings.Split(authorization[1], "=")
		if len(tokenSlice) >= 2 && len(uidSlice) >= 2 {
			uid = cast.ToInt(uidSlice[1])
		}
	}
	return uid
}

func (base Controller) GetDeviceInfo(c echo.Context) string {
	return c.Request().Header.Get("device-info")
}

func (base Controller) GetRegSource(c echo.Context) string {
	return c.Request().Header.Get("reg-source")
}

func (base Controller) GetSite(c echo.Context) string {
	return c.Request().Header.Get("site")
}

func (base Controller) GetPlatform(c echo.Context) int8 {
	if c.Request().Header.Get("platform") != "" {
		return cast.ToInt8(c.Request().Header.Get("platform"))
	}
	return cast.ToInt8(c.Request().Header.Get("Platform"))

}

// 请求超时
func (base Controller) GrpcWithTimeout() (context.Context, context.CancelFunc) {
	return context.WithTimeout(context.Background(), time.Second*60)
}
